#!/bin/bash

echo "🚀 终极构建脚本 - 明确排除所有测试文件"
echo "======================================"

# 清理
rm -rf bin .objs
mkdir -p bin .objs

# 编译设置
INCLUDES="-I../cbp2make/lib -I../cbp2make/lib/tinyxml -I../cbp2make/src -Ilib -Isrc"
CXXFLAGS="-std=c++11 -DAICODER_ENHANCED -m64"

echo "📝 编译核心文件（明确列表）..."

# 编译函数
compile() {
    local src=$1
    local obj=$2
    echo "  编译: $(basename "$src")"
    g++ $INCLUDES $CXXFLAGS -c "$src" -o "$obj" >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "    ✅ 成功"
        return 0
    else
        echo "    ❌ 失败"
        return 1
    fi
}

# 1. AI 文件
echo "🔸 AI 增强文件:"
compile "src/aicoder_enhancements.cpp" ".objs/aicoder_enhancements.o"

# 2. cbp2make 核心文件（明确列表）
echo ""
echo "🔸 cbp2make 核心文件:"
CBP_CORE_FILES=(
    "../cbp2make/src/cbp2make.cpp"
    "../cbp2make/src/cbproject.cpp" 
    "../cbp2make/src/cbworkspace.cpp"
    "../cbp2make/src/makefile.cpp"
    "../cbp2make/src/cbptarget.cpp"
    "../cbp2make/src/cbpunit.cpp"
    "../cbp2make/src/cbbuildcfg.cpp"
    "../cbp2make/src/cbbuildmgr.cpp"
    "../cbp2make/src/cbglobalvar.cpp"
    "../cbp2make/src/cbhelper.cpp"
    "../cbp2make/src/depsearch.cpp"
    "../cbp2make/src/platforms.cpp"
    "../cbp2make/src/toolchains.cpp"
    "../cbp2make/src/buildtools.cpp"
)

for file in "${CBP_CORE_FILES[@]}"; do
    base=$(basename "$file" .cpp)
    compile "$file" ".objs/$base.o"
done

# 3. STL 工具库
echo ""
echo "🔸 STL 工具库:"
STL_FILES=(
    "../cbp2make/lib/stlconfig.cpp"
    "../cbp2make/lib/stlconvert.cpp"
    "../cbp2make/lib/stlfutils.cpp"
    "../cbp2make/lib/stlgpm.cpp"
    "../cbp2make/lib/stlstrings.cpp"
    "../cbp2make/lib/stlvariables.cpp"
    "../cbp2make/lib/stringhash.cpp"
)

for file in "${STL_FILES[@]}"; do
    base=$(basename "$file" .cpp)
    compile "$file" ".objs/$base.o"
done

# 4. TinyXML 核心库（明确排除测试文件）
echo ""
echo "🔸 TinyXML 核心库:"
TINYXML_CORE_FILES=(
    "../cbp2make/lib/tinyxml/tinystr.cpp"
    "../cbp2make/lib/tinyxml/tinyxml.cpp"
    "../cbp2make/lib/tinyxml/tinyxmlerror.cpp"
    "../cbp2make/lib/tinyxml/tinyxmlparser.cpp"
    # 故意排除: "../cbp2make/lib/tinyxml/xmltest.cpp"
)

for file in "${TINYXML_CORE_FILES[@]}"; do
    base=$(basename "$file" .cpp)
    compile "$file" ".objs/$base.o"
done

echo ""
echo "🚫 明确排除的文件:"
echo "   xmltest.cpp - TinyXML 测试程序（包含冲突的 main 函数）"

# 链接
echo ""
echo "🔗 链接可执行文件..."
g++ -m64 .objs/*.o -o bin/cbp2make_ai

if [ -f "bin/cbp2make_ai" ]; then
    echo ""
    echo "🎉 终极构建成功!"
    echo "📊 统计:"
    echo "   - 对象文件: $(find .objs -name "*.o" | wc -l) 个"
    echo "   - 可执行文件: bin/cbp2make_ai"
    echo "   - 文件大小: $(du -h bin/cbp2make_ai | cut -f1)"
    echo ""
    echo "🧪 功能验证:"
    ./bin/cbp2make_ai --help 2>&1 | head -8
else
    echo "❌ 构建失败"
    g++ -m64 .objs/*.o -o bin/cbp2make_ai 2>&1 | head -10
fi

echo "======================================"
